package com.iwhalecloud.bss.kite.cucc.service.order;

import com.google.common.base.Objects;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.*;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IUnicomRegionService;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IDeliveryService;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegion;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegionQry;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalAttrHelper;
import com.iwhalecloud.bss.kite.cucc.spec.impl.transfer.GoodsInfoTransfer;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferDetailCache;
import com.iwhalecloud.bss.kite.dataservice.entity.OfferAttr;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.OfferDetail;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttrValue;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.ztesoft.bss.order.base.consts.IKeyValues;
import com.ztesoft.bss.order.base.consts.KeyValues;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DeliveryService implements IDeliveryService {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Override
    public Map<String, Object> operateDeliveryInfos(String sceneInstId, String offerInstId, String moduleId,
                                                    String instId, String actionType) {
        Map<String, Object> restMap = new HashMap();
        List<Map<String, Object>> deliveryInfos = querySceneInstService
            .getExtParameterValue(sceneInstId, "offerInstDeliveryInfos");
        if (KiteListUtils.isEmpty(deliveryInfos)) {
            deliveryInfos = new ArrayList<>();
        }
        List<KiteProdInst> kiteProdInsts = querySceneInstService.listProdInsts(sceneInstId);
        if(KiteListUtils.isEmpty(kiteProdInsts)){
            return null;
        }
        List<KiteAttr> kiteAttrs = querySceneInstService.listCommonAttrsByModuleId(sceneInstId, moduleId).stream()
            .filter(kiteAttr -> !KiteStringUtils.isEqual("H", kiteAttr.getShowType()) && !KiteStringUtils
                .isEqual("1", kiteAttr.getObjId())).collect(Collectors.toList());
        if (KiteStringUtils.isEqual(KeyConsts.ACTION_TYPE_A, actionType)) {
            kiteAttrs.stream().forEach(kiteAttr -> {
                kiteAttr.setValue("");
                kiteAttr.setValueDesc("");
                if (KiteStringUtils.isEqual("offerName", kiteAttr.getFieldName())) {
                    List<KiteAttrValue> attrValues = new ArrayList<>();
                    List<KiteOfferInst> giftOfferInsts = querySceneInstService.listGiftOfferInsts(sceneInstId);
                    if (KiteListUtils.isNotEmpty(giftOfferInsts)) {
                        giftOfferInsts.stream().forEach(giftOfferInst -> {
                            List<OfferAttr> offerAttrs = OfferCache.get(giftOfferInst.getSpecId()).listOfferAttrs().stream()
                                .filter(attr -> "cateId".equals(attr.getFieldName())).collect(Collectors.toList());
                            String cateIdStr = "";
                            if (KiteListUtils.isNotEmpty(offerAttrs)) {
                                cateIdStr = offerAttrs.get(0).getDefaultValue();
                            }
                            if (!GoodsInfoTransfer.isAddRoleOffer(giftOfferInst.getSpecId(), cateIdStr)) {
                                KiteAttrValue attrValue = new KiteAttrValue();
                                attrValue.setAttrValue(giftOfferInst.getOfferInstId());
                                attrValue.setAttrValueName(giftOfferInst.getOfferName());
                                attrValues.add(attrValue);
                            }
                        });
                    } else {
                        List<KiteOfferInst> offerInsts = querySceneInstService.listMainOfferInsts(sceneInstId);
                        offerInsts.stream().forEach(offerInst -> {
                            List<OfferAttr> offerAttrs = OfferCache.get(offerInst.getSpecId()).listOfferAttrs().stream()
                                .filter(attr -> "cateId".equals(attr.getFieldName())).collect(Collectors.toList());
                            String cateIdStr = "";
                            if (KiteListUtils.isNotEmpty(offerAttrs)) {
                                cateIdStr = offerAttrs.get(0).getDefaultValue();
                            }
                            if (!GoodsInfoTransfer.isAddRoleOffer(offerInst.getSpecId(), cateIdStr)) {
                                KiteAttrValue attrValue = new KiteAttrValue();
                                attrValue.setAttrValue(offerInst.getOfferInstId());
                                attrValue.setAttrValueName(offerInst.getOfferName());
                                attrValues.add(attrValue);
                            }
                        });
                    }
                    kiteAttr.setAttrValues(attrValues);
                }
                if (KiteStringUtils.isEqual("accNum", kiteAttr.getFieldName())) {
                    KiteAttr businessNumber = querySceneInstService.getCommonAttr(sceneInstId, "business_number");
                    kiteAttr.setValue(businessNumber.getValue());
                }
                //省
                if (KiteStringUtils.isEqual("ORD10053", kiteAttr.getFieldName())) {
                    LocalAttrHelper.initPlatformProvince(kiteAttr, kiteProdInsts.get(0).getProdId());
                }
            });
            restMap.put("instId", SeqUtils.getNext("SEQ_OFFER_INST_DELIVERY_REL_ID"));
            restMap.put("sceneInstId", sceneInstId);
            restMap.put("offerInstId", offerInstId);
            restMap.put("actionType", ActionType.A.name());
            restMap.put("kiteAttrs", kiteAttrs);
            deliveryInfos.add(restMap);
            operateSceneInstService.putExtParameter(sceneInstId, "offerInstDeliveryInfos", deliveryInfos);
        }
        if (KiteStringUtils.isEqual(KeyConsts.ACTION_TYPE_M, actionType)) {
            if (KiteListUtils.isNotEmpty(deliveryInfos)) {
                for (Map<String, Object> deliveryInfo : deliveryInfos) {
                    if (KiteStringUtils.isEqual(KiteMapUtils.getString(deliveryInfo, "instId"), instId)) {
                        List<KiteAttr> attr = (List<KiteAttr>) deliveryInfo.get("kiteAttrs");
                        if (attr.size() > 0) {
                            KiteAttr provinceAttr = querySceneInstService.getCommonAttr(sceneInstId, "ORD10053");
                            KiteAttr cityAttr = querySceneInstService.getCommonAttr(sceneInstId, "ORD10054");
                            KiteAttr countyAttr = querySceneInstService.getCommonAttr(sceneInstId, "ORD10055");
                            if(KiteObjectUtils.isEmpty(provinceAttr)|| KiteObjectUtils.isEmpty(cityAttr)|| KiteObjectUtils.isEmpty(countyAttr)){
                                return null;
                            }
                            attr.stream().forEach(data -> {
                                if (KiteStringUtils.equals("ORD10053", data.getFieldName())) {
                                    LocalAttrHelper.initPlatformProvince(data, kiteProdInsts.get(0).getProdId());
                                }
                                List<KiteAttr> provinceData = attr.stream().filter(p->(KiteStringUtils.equals(p.getFieldName(),"ORD10053"))).collect(Collectors.toList());
                                if (KiteStringUtils.equals("ORD10054", data.getFieldName())) {
                                    
                                    //地市
                                    if(!KiteListUtils.isEmpty(provinceData) && KiteStringUtils.isNotEmpty(provinceData.get(0).getValue())){
                                        LocalAttrHelper.loadPlatformCity(provinceData.get(0).getValue(), data, kiteProdInsts.get(0).getSpecId());
                                    }
                                    if (KiteListUtils.isNotEmpty(data.getAttrValues())) {
                                        List<KiteAttrValue> kiteAttrValue = data.getAttrValues().stream().filter(attrValue -> KiteStringUtils.isEqual(attrValue.getAttrValue(), data.getValue())).collect(Collectors.toList());
                                        if (KiteListUtils.isEmpty(kiteAttrValue)) {
                                            data.setValue("");
                                            data.setValueDesc("");
                                            
                                        }
                                    }
                                }
                                //区县
                                if (KiteStringUtils.equals("ORD10055", data.getFieldName())) {
                                    
                                    List<KiteAttr> cityData =  attr.stream().filter(p->(KiteStringUtils.equals(p.getFieldName(),"ORD10054"))).collect(Collectors.toList());
                                    IUnicomRegionService unicomRegionService = KiteSpringUtils.getBeanHighPriority(IUnicomRegionService.class);
                                    if(!KiteListUtils.isEmpty(cityData) && KiteStringUtils.isNotEmpty(cityData.get(0).getValue())){
                                        //List<List<UnicomRegion>> countyList = unicomRegionService.listSubRegionMulti(cityData.get(0).getValue());
                                        UnicomRegionQry regionQry = new UnicomRegionQry();
                                        regionQry.setRegionLevel(20);
                                        regionQry.setTopAreaCode(provinceData.get(0).getValue());
                                        regionQry.setParentAreaCode(cityData.get(0).getValue());
                                        regionQry.setProductId(kiteProdInsts.get(0).getSpecId());
                                        regionQry.setProdInstId(kiteProdInsts.get(0).getProdInstId());
                                        List<UnicomRegionQry> unicomRegionQryList = new ArrayList<>();
                                        unicomRegionQryList.add(regionQry);
                                        List<List<UnicomRegion>> countyList =unicomRegionService.subRegionMultiFromPlatform(unicomRegionQryList);
                                        List<KiteAttrValue> attrValues = new ArrayList<>();
                                        countyList.forEach( region -> {
                                            region.forEach( county -> {
                                                KiteAttrValue  value= new KiteAttrValue();
                                                value.setAttrValue(county.getRegionCode());
                                                value.setAttrValueDesc(county.getRegionName());
                                                attrValues.add(value);
                                            });
                                        });
                                        data.setAttrValues(attrValues);
                                        if (KiteListUtils.isNotEmpty(data.getAttrValues())) {
                                            List<KiteAttrValue> kiteAttrValue = data.getAttrValues().stream().filter(attrValue -> KiteStringUtils.isEqual(attrValue.getAttrValue(), data.getValue())).collect(Collectors.toList());
                                            if (KiteListUtils.isEmpty(kiteAttrValue)) {
                                                data.setValue("");
                                                data.setValueDesc("");
                                            }
                                        }
                                    }
                                    else {
                                        data.setValue("");
                                        data.setValueDesc("");
                                    }
                                }
                            });
                        }
                        return deliveryInfo;
                    }
                }
            }
        }
        if (KiteStringUtils.isEqual(KeyConsts.ACTION_TYPE_D, actionType)) {
            List<Map<String, Object>> delDeliveryInfos = querySceneInstService
                .getExtParameterValue(sceneInstId, "offerInstDeliveryInfosDel");
            if (KiteListUtils.isEmpty(delDeliveryInfos)) {
                delDeliveryInfos = new ArrayList<>();
            }
            if (KiteListUtils.isNotEmpty(deliveryInfos)) {
                Iterator<Map<String, Object>> it = deliveryInfos.iterator();
                while (it.hasNext()) {
                    Map<String, Object> deliveryInfo = it.next();
                    String actionTypeStr = (String) deliveryInfo.get("actionType");
                    if (ActionType.A.name().equals(actionTypeStr)) {
                        if (KiteStringUtils.isEqual((String) deliveryInfo.get("instId"), instId)) {
                            if (Objects.equal(deliveryInfo.get("isSync"), true)) {
                                deliveryInfo.put("actionType", ActionType.D.name());
                                delDeliveryInfos.add(deliveryInfo);
                            }
                            it.remove();
                            break;
                        }
                    } else if (ActionType.K.name().equals(actionTypeStr) || ActionType.M.name().equals(actionTypeStr)) {
                        if (KiteStringUtils.isEqual((String) deliveryInfo.get("instId"), instId)) {
                            deliveryInfo.put("actionType", ActionType.D.name());
                            delDeliveryInfos.add(deliveryInfo);
                            it.remove();
                            break;
                        }
                    }
                }
                // 删除时要清空属性的值
                kiteAttrs.forEach(kiteAttr -> {
                    operateSceneInstService.setCommonAttrValue(sceneInstId, kiteAttr.getFieldName(), "", "");
                });
                operateSceneInstService.putExtParameter(sceneInstId, "offerInstDeliveryInfos", deliveryInfos);
                operateSceneInstService.putExtParameter(sceneInstId, "offerInstDeliveryInfosDel", delDeliveryInfos);
            }
        }
        return restMap;
    }

    @Override
    public Map<String, Object> getDeliveryInfosList(String sceneInstId) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<Map<String, Object>> deliveryInfos = querySceneInstService
            .getExtParameterValue(sceneInstId, "offerInstDeliveryInfos");
        if (KiteListUtils.isNotEmpty(deliveryInfos)) {
            for (Map<String, Object> deliveryInfo : deliveryInfos) {
                Map<String, Object> map = new HashMap<>();
                map.put("instId", KiteMapUtils.getString(deliveryInfo, "instId"));
                List<KiteAttr> kiteAttrs = (List<KiteAttr>) deliveryInfo.get("kiteAttrs");
                StringBuilder builder = new StringBuilder();
                String provinceValueDesc = "";
                String cityValueDesc = "";
                String countyValueDesc = "";
                String remarkValueDesc = "";
                for (KiteAttr attr : kiteAttrs) {
                    if (KiteStringUtils.isEmpty(attr.getObjId())) {
                        if (KiteStringUtils.equals(attr.getAttrValueTypeId(), KeyValues.DROPDOWN)) {
                            map.put(attr.getFieldName(),
                                KiteStringUtils.isEmpty(attr.getValue()) ? "" : attr.getValueDesc());
                        } else {
                            map.put(attr.getFieldName(),
                                KiteStringUtils.isEmpty(attr.getValue()) ? "" : attr.getValue());
                        }
                    } else {
                        if(KiteStringUtils.equals("ORD10053",attr.getFieldName())){

                            provinceValueDesc = KiteStringUtils.isEmpty(attr.getValue()) ? "" : attr.getValueDesc();
                        }
                        if(KiteStringUtils.equals("ORD10054",attr.getFieldName())){
                            cityValueDesc = KiteStringUtils.isEmpty(attr.getValue()) ? "" : attr.getValueDesc();
                        }
                        if(KiteStringUtils.equals("ORD10055",attr.getFieldName())){
                            countyValueDesc = KiteStringUtils.isEmpty(attr.getValue()) ? "" : attr.getValueDesc();
                        }
                        if(KiteStringUtils.equals("ORD10040",attr.getFieldName())){
                            remarkValueDesc = KiteStringUtils.isEmpty(attr.getValue()) ? "" : attr.getValueDesc();
                        }
                    }
                }

                String deliveryAddress = builder.append(provinceValueDesc).append(cityValueDesc).append(countyValueDesc).append(remarkValueDesc).toString();
                map.put("deliveryAddress", deliveryAddress);
                resultList.add(map);
                resultMap.put("isShowBtn", querySceneInstService.getExtParameterValue(sceneInstId, "deliveryInfosBtnShowFlag"));
                resultMap.put("deliveryInfos", resultList);
            }
        }
        return resultMap;
    }

    @Override
    public Boolean autogenerationDeliveryInfos(String sceneInstId) {
        try {
            List<KiteOfferInst> listGiftOfferInsts = querySceneInstService.listGiftOfferInsts(sceneInstId);
            List<Map<String, Object>> deliveryInfos = querySceneInstService
                .getExtParameterValue(sceneInstId, "offerInstDeliveryInfos");
            String isShowBtn = "F";
            if (KiteListUtils.isNotEmpty(deliveryInfos)) {
                if (KiteListUtils.isNotEmpty(listGiftOfferInsts)) {
                    //融合商品默认展示添加收货信息按钮
                    isShowBtn = "T";
                    boolean hasDelivery = false;
                    String giftOfferId = listGiftOfferInsts.get(0).getOfferId();
                    List<KiteProdInst> prodInstList = querySceneInstService.listProdInsts(sceneInstId);
                    for (KiteProdInst prodInst : prodInstList) {
                        KiteAttr attr = prodInst.getAttr("200004110");
                        if (!KiteObjectUtils.isEmpty(attr)) {
                            String value = attr.getValue();
                            if (KiteStringUtils.equals(value, "100007295")) {
                                hasDelivery = true;
                                //融合商品组合发货不展示添加收货信息按钮
                                isShowBtn = "F";
                                break;
                            }
                        }
                    }
//                    List<OfferDetail> list = OfferDetailCache.get(giftOfferId);
                    if (hasDelivery) {
//                        List<KiteOfferInst> offerInsts = querySceneInstService.listMainOfferInsts(sceneInstId);
//                        if (KiteListUtils.isNotEmpty(offerInsts)) {
//                            for (KiteOfferInst offerInst : offerInsts) {
//                                boolean hasRel = false;
//                                String offerId = offerInst.getOfferId();
//                                if (KiteListUtils.isNotEmpty(list)) {
//                                    for (OfferDetail detail : list) {
//                                        String objId = detail.getObjId();
//                                        if (KiteStringUtils.equals(offerId, objId)) {
//                                            hasRel = true;
//                                            break;
//                                        }
//                                    }
//                                }
//                                if (!hasRel) {
//                                    continue;
//                                }
//                                boolean hasDeliveryInfo = false;
//                                for (Map<String, Object> deliveryInfo : deliveryInfos) {
//                                    List<KiteAttr> kiteAttrs = (List<KiteAttr>) deliveryInfo.get("kiteAttrs");
//                                    for (KiteAttr kiteAttr : kiteAttrs) {
//                                        if (KiteStringUtils.isEqual("offerName", kiteAttr.getFieldName())) {
//                                            if (KiteStringUtils
//                                                .equals(kiteAttr.getValue(), offerInst.getOfferInstId())) {
//                                                hasDeliveryInfo = true;
//                                                break;
//                                            }
//                                        }
//                                    }
//                                    if (hasDeliveryInfo) {
//                                        break;
//                                    }
//                                }
//                                if (!hasDeliveryInfo) {
//                                    dealDeliveryInfo(sceneInstId, deliveryInfos, offerInst);
//                                }
//                            }
//                        }
                        // 补充礼包本身的收货信息
                        listGiftOfferInsts.stream().forEach(giftOfferInst -> {
                            boolean flag = true;
                            if (KiteListUtils.isNotEmpty(deliveryInfos)) {
                                for (Map deliveryInfoMap : deliveryInfos) {
                                    List<KiteAttr> kiteAttrs = (List<KiteAttr>) deliveryInfoMap.get("kiteAttrs");
                                    for (KiteAttr kiteAttr : kiteAttrs) {
                                        if (KiteStringUtils.isEqual("offerName", kiteAttr.getFieldName())) {
                                            if (KiteStringUtils
                                                .equals(kiteAttr.getValue(), giftOfferInst.getOfferInstId())) {
                                                flag = false;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            if (flag) {
                                dealDeliveryInfo(sceneInstId, deliveryInfos, giftOfferInst);
                            }
                        });
                        operateSceneInstService.putExtParameter(sceneInstId, "offerInstDeliveryInfos", deliveryInfos);
                    }
                }
            }
            operateSceneInstService.putExtParameter(sceneInstId, "deliveryInfosBtnShowFlag", isShowBtn);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    private void dealDeliveryInfo(String sceneInstId, List<Map<String, Object>> deliveryInfos,
                                  KiteOfferInst offerInst) {
        List<KiteAttr> kiteAttrs = (List<KiteAttr>) deliveryInfos.get(0).get("kiteAttrs");
        List<KiteAttr> cloneList = KiteObjectUtils.clone(kiteAttrs);
        for (KiteAttr cloneAttr : cloneList) {
            if (KiteStringUtils.isEqual("offerName", cloneAttr.getFieldName())) {
                cloneAttr.setValue(offerInst.getOfferInstId());
                cloneAttr.setValueDesc(offerInst.getOfferName());
            }
        }
        Map<String, Object> restMap = new HashMap();
        restMap.put("instId", SeqUtils.getNext("SEQ_OFFER_INST_DELIVERY_REL_ID"));
        restMap.put("sceneInstId", sceneInstId);
        restMap.put("offerInstId", offerInst.getOfferInstId());
        restMap.put("actionType", ActionType.A.name());
        restMap.put("kiteAttrs", cloneList);
        deliveryInfos.add(restMap);
    }
}
